package com.tjp.mall.product.service.impl;

import com.mysql.cj.util.StringUtils;
import com.tjp.mall.product.entity.AttrGroupEntity;
import com.tjp.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjp.common.utils.PageUtils;
import com.tjp.common.utils.Query;

import com.tjp.mall.product.dao.BrandDao;
import com.tjp.mall.product.entity.BrandEntity;
import com.tjp.mall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("brand_id", key).or().like("name", key);
            });
        }


        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void removeBrandByIds(List<Long> asList) {
        //TODO  检查类别数据是否在其他业务中使用

        //批量逻辑删除操作
        baseMapper.deleteBatchIds(asList);
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        //先更新原始数据
        this.updateById(brand);

        //更新时,查询品牌分类关联表,如果有关联数据,同步更新brand_name
        String name = brand.getName();
        if (!StringUtils.isNullOrEmpty(name)) {
            Long brandId = brand.getBrandId();
            categoryBrandRelationService.updateBrandNameByBrandId(brandId, name);

            // TODO 同步更新其他冗余数据
        }
    }
}